import sys
import json
import math
# pip install Pillow
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
from collections import Counter

def quantize_number(num , decimal_num) -> str:
    return round(num, decimal_num)

def analysis_img_info(image_path, decimal_num):
    # 打开图片并获取所有像素数据
    im = Image.open(image_path)
    pixels = list(im.getdata())
    # 移除所有数据小于等于0的像素(背景或无效值)
    pixels = [pixel for pixel in pixels if pixel > 0.0]
    # 修正数据，步长为0.01，用来减少需要储存的数量，即15.265和15.264978均会被转为15.26
    quantize_numbers = [quantize_number(num, decimal_num) for num in pixels]
    # 统计每个数据出现的次数，减少重复项的录入，用于减少储存的数据
    data_counter = Counter(quantize_numbers)
    # 组合为对象
    data_list = {data: count for data, count in data_counter.items()}
    return data_list

def group_by_interval(dataInfo, interval):

    intervalSumMap  = {}
    # 遍历原始 JSON 对象的每个键值对
    for key, value in dataInfo.items():
        # 将键转换为对应的区间
        intervalKey = math.floor(float(key) / interval) * interval
        # 将值累加到该区间对应的总和中
        intervalSumMap[intervalKey] = intervalSumMap.get(intervalKey, 0) + value

    return intervalSumMap

if __name__ == '__main__':
    # image_path = './LAI.tif'
    # image_path = './odm_orthophoto.original.tif'
    image_path = sys.argv[1]
    decimal_num = 2
    analysis_result = analysis_img_info(image_path, decimal_num)
    print(json.dumps(analysis_result))

    # print("原始数据：{}".format(json.dumps(analysis_result)))
    # # 定义区间间隔
    # interval = 0.5
    # # 将数据按照区间分组并计算每个区间的总数
    # intervalSumMap = group_by_interval(analysis_result, interval)
    # # 计算所有值的总和
    # allSum = sum(analysis_result.values())
    # print("所有值的总和：{}".format(allSum))
    # # 打印每个区间对应的总和
    # for intervalKey, intervalSum in sorted(intervalSumMap.items()):
    #     print("区间：{} - {}，总和：{}，占总比的 {:.2f}%".format(intervalKey, intervalKey + interval, intervalSum, (intervalSum / allSum) * 100))